import { reactive, computed, ref, onMounted, onUnmounted } from 'vue'
import { useBreakpoints } from '@vueuse/core'

// 使用 Tailwind 的默认断点
export const breakpointsEnum = {
  '2xl': 1536,
  xl: 1280,
  lg: 1024,
  md: 768,
  sm: 640,
  xs: 375,
} as const

export const useScreenStore = () => {
  // 使用 ref 存储窗口尺寸，使其具有响应性
  const windowWidth = ref(window.innerWidth)
  const windowHeight = ref(window.innerHeight)

  const breakpoints = reactive(useBreakpoints(breakpointsEnum))

  // 获取当前断点
  function getCurrentBreakpoint() {
    if (windowWidth.value >= breakpointsEnum['2xl']) return '2xl'
    if (windowWidth.value >= breakpointsEnum.xl) return 'xl'
    if (windowWidth.value >= breakpointsEnum.lg) return 'lg'
    if (windowWidth.value >= breakpointsEnum.md) return 'md'
    if (windowWidth.value >= breakpointsEnum.sm) return 'sm'
    return 'xs'
  }

  // 获取设备类型
  function getDeviceType() {
    if (windowWidth.value >= breakpointsEnum.xl) return 'desktop'
    if (windowWidth.value >= breakpointsEnum.lg) return 'laptop'
    if (windowWidth.value >= breakpointsEnum.sm) return 'tablet'
    return 'mobile'
  }

  // 添加防抖函数
  function debounce(fn: Function, delay: number) {
    let timer: ReturnType<typeof setTimeout>
    return function (this: any, ...args: any[]) {
      clearTimeout(timer)
      timer = setTimeout(() => fn.apply(this, args), delay)
    }
  }

  // 更新窗口尺寸的处理函数
  const updateWindowSize = debounce(() => {
    windowWidth.value = window.innerWidth
    windowHeight.value = window.innerHeight
  }, 100) // 100ms 的防抖延迟

  // 组件挂载时添加事件监听
  onMounted(() => {
    window.addEventListener('resize', updateWindowSize)
  })

  // 组件卸载时移除事件监听
  onUnmounted(() => {
    window.removeEventListener('resize', updateWindowSize)
  })

  const screen = computed(() => {
    const deviceType = getDeviceType()

    return {
      // 设备类型判断
      isMobile: deviceType === 'mobile',
      isTablet: deviceType === 'tablet',
      isLaptop: deviceType === 'laptop',
      isDesktop: deviceType === 'desktop',

      // 方向判断
      isPortrait: windowHeight.value > windowWidth.value,
      isLandscape: windowWidth.value > windowHeight.value,

      // 当前断点
      current: getCurrentBreakpoint(),

      // 当前设备类型
      deviceType,

      // 窗口尺寸
      width: windowWidth.value,
      height: windowHeight.value,

      // 原始断点对象
      breakpoints,
    }
  })

  return screen
}

// 使用示例
/*
const screen = useScreenStore()

watchEffect(() => {
  const { deviceType, width, current } = screen.value
  console.log(`当前设备: ${deviceType}`)
  console.log(`当前宽度: ${width}px`)
  console.log(`当前断点: ${current}`)
})
*/
